import useMount from "../../hooks/useMount"
import Session from "../Session"
import { useEffect, useState } from "react"
import * as echarts from "echarts"
import { useRef } from "react"
import Card from "./Card"
import "./index.css"
import { Button, Modal, Table, Collapse } from "antd"
import Management from "./Management"
import ReactMarkdown from "react-markdown"
import remarkBreaks from "remark-breaks"

// import managementAspects from "../../managementAspects.json";

// eslint-disable-next-line no-unused-vars
const option = (dataX = [], dataY1 = [], dataY2 = []) => ({
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "cross",
      crossStyle: {
        color: "#999"
      }
    }
  },
  // legend: {
  //   data: ['问题数量', '已解决']
  // },

  grid: {
    left: "6%",
    right: "6%",
    bottom: "16%"
  },
  xAxis: [
    {
      type: "category",
      data: dataX,
      axisPointer: {
        type: "shadow"
      },
      axisTick: {
        alignWithLabel: true,
        show: false
      }
    }
  ],
  yAxis: [
    {
      type: "value",
      name: "问题数量",
      min: 0,
      // max: Math.max(...dataY1) + 3,
      // interval: 3,

      axisLabel: {}
    }
    // {
    //   type: 'value',
    //   name: '已解决',
    //   min: 0,
    //   // max: 50,
    //   // interval: 10,
    //   axisLabel: {

    //   }
    // }
  ],
  series: [
    {
      name: "问题数量",
      type: "bar",
      data: dataY1,
      barWidth: "24%",
      itemStyle: {
        color: {
          type: "linear",
          x: 0, // 从左开始
          y: 0, // 从下开始
          x2: 0, // 到右结束
          y2: 1, // 到上结束
          colorStops: [
            {
              offset: 0,
              color: "rgba(0, 200, 255, 1)" // 起始颜色
            },
            {
              offset: 1,
              color: "rgba(58, 77, 233, 1)" // 结束颜色
            }
          ]
        }
      }
    }
    // {
    //   name: '已解决',
    //   type: 'line',
    //   yAxisIndex: 1,
    //   data: dataY2, //[10, 20, 25, 30, 40, 45],
    //   symbolSize: 10,
    //   itemStyle: {
    //     color: '#803FF4',
    //     borderColor: '#803FF4',
    //     borderWidth: 2
    //   },
    //   lineStyle: {
    //     color: '#803FF4',
    //     width: 3,
    //     type: 'solid'
    //   }
    // }
  ]
})

// prettier-ignore
let dataAxis = ['2021', '2022', '2023', '2024'];
// prettier-ignore
let data = [220, 182, 191, 234];
let yMax = 500
let dataShadow = []
for (let i = 0; i < data.length; i++) {
  dataShadow.push(yMax)
}
const option1 = {
  xAxis: {
    data: dataAxis,
    // axisLabel: {
    //   inside: true,
    //   color: '#fff'
    // },
    axisTick: {
      show: false
    },
    axisLine: {
      show: false
    },
    z: 10
  },
  yAxis: {
    axisLine: {
      show: false
    },
    axisTick: {
      show: false
    },
    axisLabel: {
      color: "#999"
    }
  },
  dataZoom: [
    {
      type: "inside"
    }
  ],
  series: [
    {
      type: "bar",
      barWidth: 20, // 设置柱子宽度为20px

      showBackground: false,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: "#83bff6" },
          { offset: 0.5, color: "#188df0" },
          { offset: 1, color: "#188df0" }
        ])
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#2378f7" },
            { offset: 0.7, color: "#2378f7" },
            { offset: 1, color: "#83bff6" }
          ])
        }
      },
      data: data
    }
  ]
}

const option3 = {
  xAxis: {
    type: "category",
    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  },
  yAxis: {
    type: "value"
  },
  series: [
    {
      data: [
        120,
        {
          value: 200,
          itemStyle: {
            color: "#a90000"
          }
        },
        150,
        80,
        70,
        110,
        130
      ],
      type: "bar"
    }
  ]
}

const option4 = {
  legend: {},
  tooltip: {},
  dataset: {
    source: [
      ["product", "物资挤压", "虚假利库", "有物无账"],
      ["2021", 43.3, 85.8, 93.7],
      ["2022", 83.1, 73.4, 55.1]
    ]
  },
  xAxis: { type: "category" },
  yAxis: {},
  // Declare several bar series, each will be mapped
  // to a column of dataset.source by default.
  series: [
    { type: "bar", barWidth: 20 },
    { type: "bar", barWidth: 20 },
    { type: "bar", barWidth: 20 }
  ]
}

const option5 = (list = []) => ({
  legend: {},
  tooltip: {},
  dataset: {
    source: [
      ["category", "未整改", "整改中", "完成整改"],
      ...list
      // ['2021', 43.3, 85.8, 93.7],
      // ['2022', 83.1, 73.4, 55.1],
    ]
  },
  xAxis: { type: "category" },
  yAxis: {},
  // Declare several bar series, each will be mapped
  // to a column of dataset.source by default.
  series: [
    { type: "bar", barWidth: 20 },
    { type: "bar", barWidth: 20 },
    { type: "bar", barWidth: 20 }
  ]
})

// 渲染数据来源列表组件
const RenderDataSource = ({ dataSource }) => {
  // 检查dataSource是否为数组
  if (!Array.isArray(dataSource)) {
    try {
      // 尝试解析JSON字符串
      const parsedData =
        typeof dataSource === "string" ? JSON.parse(dataSource) : dataSource
      if (Array.isArray(parsedData)) {
        dataSource = parsedData
      } else {
        return <div>数据格式不正确</div>
      }
      // eslint-disable-next-line no-unused-vars
    } catch (e) {
      return <div>无法解析数据来源</div>
    }
  }

  // 如果数据源是简单字符串数组，显示为列表
  if (dataSource.length > 0 && typeof dataSource[0] === "string") {
    return (
      <div className="data-source-list">
        <h3 className="text-lg font-bold mb-4">问题编号列表</h3>
        <ul className="list-disc pl-6">
          {dataSource.map((item, index) => (
            <li key={index} className="mb-2">
              {item}
            </li>
          ))}
        </ul>
      </div>
    )
  }

  // 如果是AuditProblemDetailVO对象数组，显示为表格
  // 获取第一个对象的所有字段，用于生成表头
  const allFields = dataSource.length > 0 ? Object.keys(dataSource[0]) : []

  // 定义字段宽度映射
  const fieldWidthMap = {
    problemCode: "8%",
    occurrenceYear: "6%",
    projectName: "10%",
    projectType: "6%",
    projectYear: "6%",
    problemNature: "8%",
    problemFirstCategory: "8%",
    problemAspect: "8%",
    problemFourthCategory: "8%",
    rectificationCategory: "8%",
    problemSummary: "15%",
    policyBasis: "15%",
    auditOpinion: "15%",
    rectificationStatus: "6%",
    rectificationMeasures: "15%",
    rectificationPlan: "15%",
    auditedUnit: "10%"
  }

  return (
    <div className="data-source-detail">
      <h3 className="text-lg font-bold mb-4">审计问题详情列表</h3>

      <div className="data-source-table-container">
        {/* 表格头部 */}
        <div className="data-source-table-header">
          {allFields.map((field, index) => (
            <div
              key={index}
              className="data-source-table-header-cell"
              style={{
                width: fieldWidthMap[field] || `${100 / allFields.length}%`
              }}
            >
              {getFieldDisplayName(field)}
            </div>
          ))}
        </div>

        {/* 表格内容 */}
        <div className="data-source-table-body">
          {dataSource.map((problem, rowIndex) => (
            <div key={rowIndex} className="data-source-table-row">
              {allFields.map((field, cellIndex) => (
                <div
                  key={cellIndex}
                  className="data-source-table-cell"
                  style={{
                    width: fieldWidthMap[field] || `${100 / allFields.length}%`
                  }}
                >
                  {renderCellContent(problem[field])}
                </div>
              ))}
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}

// 获取字段的显示名称
const getFieldDisplayName = (fieldName) => {
  const displayNames = {
    problemCode: "问题编号",
    occurrenceYear: "发生年度",
    projectName: "项目名称",
    projectType: "项目类型",
    projectYear: "项目年度",
    problemNature: "问题定性",
    problemFirstCategory: "问题一级分类",
    problemAspect: "问题方面",
    problemFourthCategory: "问题四级分类",
    rectificationCategory: "问题整改分类",
    problemSummary: "问题概述",
    policyBasis: "政策依据",
    auditOpinion: "审计意见",
    rectificationStatus: "整改状态",
    rectificationMeasures: "整改措施",
    rectificationPlan: "整改推进计划",
    auditedUnit: "审计计量单位"
  }

  return displayNames[fieldName] || fieldName
}

// 渲染单元格内容
const renderCellContent = (content) => {
  if (content === null || content === undefined) {
    return "" // 返回空字符串，不显示不存在的字段
  }

  // 处理服务端返回的文本，移除多余的引号
  if (typeof content === "string") {
    content = cleanQuotes(content)

    // 检测文本是否为长文本（超过100个字符或包含换行符）
    const isLongText = content.length > 100 || content.includes("\n")

    // 如果是长文本，使用ReactMarkdown渲染，并放在有滚动条的容器中
    if (isLongText) {
      return (
        <div className="markdown-content">
          <ReactMarkdown remarkPlugins={[remarkBreaks]}>
            {content.replace(/\n/g, "  \n")}
          </ReactMarkdown>
        </div>
      )
    }
  }

  return content
}

// 处理服务端返回文本中多余的引号问题
const cleanQuotes = (text) => {
  if (!text || typeof text !== "string") return text

  // 如果文本以引号开头和结尾，去除这些引号
  if (
    (text.startsWith('"') && text.endsWith('"')) ||
    (text.startsWith("'") && text.endsWith("'"))
  ) {
    return text.slice(1, -1)
  }

  return text
}

const riskMap = {
  compliance: "合规",
  financial: "财务",
  internal_control: "内部控制",
  it_security: "信息安全",
  operational: "运营"
}

// eslint-disable-next-line react-refresh/only-export-components
export const getCategoryData = (riskCategoriesData, category) => {
  return Object.entries(riskCategoriesData).reduce((acc, cur) => {
    const [key, val] = cur
    if (val.severity === category) {
      acc.push({
        name: riskMap[key],
        count: val.count || 0,
        compare: "优秀"
      })
    }
    return acc
  }, [])
}

const Risk = ({
  riskCategoriesData = {},
  riskTrendsData,
  textContent,
  managementAspects = []
}) => {
  // console.log("managementAspects", managementAspects)

  const {
    riskAnalysisText
    // conclusionsText,
    // auditScopeText,
    // recommendationsText,
    // auditMethodText,
  } = textContent
  const chart1 = useRef(null)
  const chart2 = useRef(null)
  const chart3 = useRef(null)
  const chart4 = useRef(null)
  const chart5 = useRef(null)

  const [open, setOpen] = useState(false)
  const [isDataSourceModalOpen, setIsDataSourceModalOpen] = useState(false)
  const [dataSourceContent, setDataSourceContent] = useState(null)

  const hasManagementAspects = managementAspects && managementAspects.length > 0

  const myChart1 = useRef(null)
  useEffect(() => {
    if (chart1.current) {
      const { chartItems = [] } = riskCategoriesData
      const dataX = chartItems.map((item) => item.aspectName || "未知")
      const dataY = chartItems.map((item) => item.count || 0)
      if (!myChart1.current) {
        myChart1.current = echarts.init(chart1.current)
      }
      myChart1.current.setOption(option(dataX, dataY))
    }
  }, [riskCategoriesData])

  const myChart5 = useRef(null)
  useEffect(() => {
    if (chart5.current) {
      const listData = Object.entries(riskTrendsData).reduce((acc, cur) => {
        const [key, val] = cur
        if (key === "improvement") {
          return acc
        }
        acc.push([key, val.empty || 0, val.inProgress || 0, val.completed || 0])
        return acc
      }, [])
      if (!myChart5.current) {
        myChart5.current = echarts.init(chart5.current)
      }
      myChart5.current.setOption(option5(listData))
    }
  }, [riskTrendsData])

  useMount(() => {
    if (chart2.current) {
      echarts.init(chart2.current).setOption(option1)
    }

    if (chart3.current) {
      echarts.init(chart3.current).setOption(option3)
    }

    if (chart4.current) {
      echarts.init(chart4.current).setOption(option4)
    }
  })

  const { highRiskItems, mediumRiskItems, lowRiskItems } = riskCategoriesData

  const [title, setTitle] = useState("")
  const [content, setContent] = useState("")
  const [contentType, setContentType] = useState("text") // 'text' 或 'dataSource'

  // const handleReasonButton = () => {
  //   setOpen(true)
  //   setTitle("问题产生的深层次原因")
  //   setContent(auditMethodText)
  //   setContentType("text")
  // }

  // const handleRecommendButton = () => {
  //   setOpen(true)
  //   setTitle("针对性整改措施与建议")
  //   setContent(recommendationsText)
  //   setContentType("text")
  // }

  // const handleSourceButton = () => {
  //   setOpen(true)
  //   setTitle("数据来源")
  //   setContent(auditScopeText)
  //   setContentType("text")
  // }

  const onPenDialog = (type, content) => {
    if (type === "source") {
      // 对于数据来源，使用单独的弹窗
      setDataSourceContent(content)
      setIsDataSourceModalOpen(true)
    } else {
      setContent(content)
      if (type === "reason") {
        setTitle("问题产生的深层次原因")
        setContentType("text")
      } else if (type === "suggest") {
        setTitle("针对性整改措施与建议")
        setContentType("text")
      }
      setOpen(true)
    }
  }

  const renderMarkdown = (text) => {
    if (!text || text === "") return text

    // 处理特殊的**加粗语法（保持原有功能）
    if (text.includes("**")) {
      const lines = text.split("**")
      if (lines.length === 0) return text
      return lines.map((line, index) => {
        if (index % 2 === 1) {
          return (
            <span key={index} className="font-bold text-blue-500">
              {line}
            </span>
          )
        } else {
          return line
        }
      })
    }

    // 预处理文本，确保换行符被正确处理
    const processedText = text.replace(/\n/g, "  \n") // Markdown需要在行尾添加两个空格才能换行

    // 使用ReactMarkdown解析，添加remarkBreaks插件支持换行
    return (
      <div className="markdown-content">
        <ReactMarkdown remarkPlugins={[remarkBreaks]}>
          {processedText}
        </ReactMarkdown>
      </div>
    )
  }

  return (
    <Session
      title="三、主要风险"
      className="w-[914px] h-[640px]"
      style={{
        backgroundImage: `url('right_inner.png')`,
        backgroundSize: "contain"
      }}
    >
      <div className="h-[580px] overflow-y-scroll scrollbar-hide">
        <h3 className="text-lg text-center font-bold my-1">
          审计发现问题综合分析
        </h3>
        <div className="px-5 py-3 mx-5 text-sm  hexagon">
          {riskAnalysisText}
        </div>
        <div ref={chart1} className="w-full h-[300px] mt-4"></div>
        <div className="flex gap-4 flex-wrap mx-5 mb-10 relative">
          {/* <Card className="w-[48%]" title="管理较好方面" titleClassName="bg-[#9cbffe]" itemColor="bg-[#eaf4fe]" /> */}
          <Card
            className="w-[48%]"
            title="管理较好"
            titleClassName="bg-[#f4b676]"
            itemColor="bg-[#fef6ea]"
            textColor="text-[#f4b676]"
            list={lowRiskItems}
          />
          <Card
            className="w-[48%]"
            title="管理薄弱"
            titleClassName="bg-[#ffa184]"
            itemColor="bg-[#FEF6EA]"
            textColor="text-[#ffa184]"
            list={mediumRiskItems}
          />
          <Card
            className="w-[48%]"
            title="问题严重"
            titleClassName="bg-[#f4887a]"
            itemColor="bg-[#FEF6EA]"
            textColor="text-[#f4887a]"
            list={highRiskItems}
          />
        </div>
        {hasManagementAspects &&
          managementAspects.map((item, index) => (
            <Management
              key={index}
              item={item}
              index={index}
              onPenDialog={onPenDialog}
            />
          ))}
        {/* <section className="mb-12 mx-5">
          <h3 className="text-lg font-bold mb-2">风险趋势</h3>
          <div className="p-5 border-dashed border">
            <h4 className="text-md font-bold">结论</h4>
            <p>{conclusionsText}</p>
          </div>
          <div ref={chart5} className="w-full h-[300px]"></div>
          <footer className="flex justify-center text-sm">
            <div className="py-1 px-5 rounded-4xl border border-gray-400 mx-2 cursor-pointer" onClick={handleReasonButton}>原因</div>
            <div className="py-1 px-5 rounded-4xl border border-gray-400 mx-2 cursor-pointer" onClick={handleRecommendButton}>建议</div>
            <div className="py-1 px-5 rounded-4xl border border-gray-400 mx-2 cursor-pointer" onClick={handleSourceButton}>数据来源</div>
          </footer>
        </section> */}

        {/* <section className="mb-4 mx-5">
          <h3 className="text-lg font-bold mb-2">（一）工程项目前期手续未完成，未核先招、未批先招</h3>
          <div className="p-5 border-dashed border">
            <h4 className="text-md font-bold">结论</h4>
            <p>年期间，持续存在招标采购管理不规范的问题，主要集中体现在评标过程不严谨（评分不一致、未按标准执行、把关不严）和程序执行倒置（未审批先采购、先开工后招标、合同未经审批先签订）两个方面。其中，</p>
          </div>
          <div ref={chart2} className="w-full h-[300px]"></div>
          <footer className="flex justify-center text-sm">
            <div className="py-1 px-5 rounded-4xl border mx-2 cursor-pointer">原因</div>
            <div className="py-1 px-5 rounded-4xl border mx-2 cursor-pointer">建议</div>
            <div className="py-1 px-5 rounded-4xl border mx-2 cursor-pointer">数据来源</div>
          </footer>
        </section>
        <section className="mb-4 mx-5">
          <h3 className="text-lg font-bold mb-2">（二） 物资及采购管理-采购计划管理</h3>
          <div className="p-5 border-dashed border">
            <h4 className="text-md font-bold">结论</h4>
            <p>该公司2020-2024年期间招标采购管理问题频发，主要表现为:一是应招未招问题突出(监控设备、印刷、工程项目、物资采购等);
              二是程序执行不规范(中介机构、供应商选定未履行程序;采购超限或变通列账);三是合同管控不严(增补合同超比例、甲供转乙供金额较大)。
              其中，2020年、2022年和2024年问题较为集中，涉及物资采购、工程项目建设等多个业务领域，特别是2024年出现违规转供物资 (金额1110万元)的新问题，显示出采购管理执行弱化趋势，招标程序流干形式，存在较大合规风险和廉政风险。</p>
          </div>
          <div ref={chart3} className="w-full h-[300px]"></div>
          <footer className="flex justify-center text-sm">
            <div className="py-1 px-5 rounded-4xl border mx-2 cursor-pointer">原因</div>
            <div className="py-1 px-5 rounded-4xl border mx-2 cursor-pointer">建议</div>
            <div className="py-1 px-5 rounded-4xl border mx-2 cursor-pointer">数据来源</div>
          </footer>
        </section>
        <section className="mb-12 mx-5">
          <h3 className="text-lg font-bold mb-2">（三）物资及采购管理-物资仓储管理方面</h3>
          <div className="p-5 border-dashed border">
            <h4 className="text-md font-bold">结论</h4>
            <p>该公司2020-2024年期间物资管理问题持续高发，集中表现为库存物资账实不符问题(2020-2024年连年出现)，
              包括出入库记录缺失领用未下账、有物无账等情形。值得注意的是，2020年配电网项目物资积压585.34万元，
              到2022年又出现通过虚假利库(416.8万元和有物无账(468.82万元)等方式调节考核指标的情况，反映出物资管理水平逐年下滑，管理混乱程度加剧。
              这些问题表明公司物资管理基础薄弱，存在存货流失和财务数据失真风险，且可能影响经营考核的真实性。</p>
          </div>
          <div ref={chart4} className="w-full h-[300px]"></div>
          <footer className="flex justify-center text-sm">
            <div className="py-1 px-5 rounded-4xl border mx-2 cursor-pointer">原因</div>
            <div className="py-1 px-5 rounded-4xl border mx-2 cursor-pointer">建议</div>
            <div className="py-1 px-5 rounded-4xl border mx-2 cursor-pointer">数据来源</div>
          </footer>
        </section> */}
      </div>
      <Modal
        wrapClassName="risk-modal-wrapper risk-modal-large"
        styles={{
          backgroundColor: "#fefefe"
        }}
        cancelText=""
        okText=""
        centered
        open={open}
        onOk={() => setOpen(false)}
        onCancel={() => setOpen(false)}
        width="80%"
        footer={
          <div className="flex justify-center items-center">
            <Button
              style={{
                backgroundColor: "#356DEE",
                width: "160px",
                height: "52px",
                fontSize: "24px",
                padding: "10px 20px"
              }}
              type="primary"
              onClick={() => setOpen(false)}
            >
              确认
            </Button>
          </div>
        }
      >
        <div className="p-10 h-[700px] flex flex-col">
          <h1 className="text-4xl font-bold text-[#6C9BDD] text-center mb-12">
            {title}
          </h1>
          <div className="bg-white rounded-4xl p-10 flex-1 overflow-auto">
            {contentType === "text" ? (
              <div className="whitespace-pre-line">
                {renderMarkdown(content)}
              </div>
            ) : (
              <RenderDataSource dataSource={content} />
            )}
          </div>
        </div>
      </Modal>

      {/* 数据来源专用弹窗 */}
      <Modal
        wrapClassName="risk-modal-wrapper data-source-modal"
        styles={{
          backgroundColor: "#fefefe"
        }}
        cancelText=""
        okText=""
        centered
        open={isDataSourceModalOpen}
        onOk={() => setIsDataSourceModalOpen(false)}
        onCancel={() => setIsDataSourceModalOpen(false)}
        width="95%"
        footer={
          <div className="flex justify-center items-center">
            <Button
              style={{
                backgroundColor: "#356DEE",
                width: "160px",
                height: "52px",
                fontSize: "24px",
                padding: "10px 20px"
              }}
              type="primary"
              onClick={() => setIsDataSourceModalOpen(false)}
            >
              确认
            </Button>
          </div>
        }
      >
        <div className="p-6 h-[850px] flex flex-col">
          <h1 className="text-4xl font-bold text-[#6C9BDD] text-center mb-8">
            数据来源
          </h1>
          <div className="bg-white rounded-4xl p-6 flex-1 overflow-hidden data-source-container">
            <RenderDataSource dataSource={dataSourceContent} />
          </div>
        </div>
      </Modal>
    </Session>
  )
}

export default Risk
